/**
 * 
 */
package com.nari.heatshare.dao.springjdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.RowCallbackHandler;

import com.nari.coreframe.dao.springjdbc.AbstractDaoImpl;
import com.nari.coreframe.dao.springjdbc.extendcore.ResultSetMapHandler;
import com.nari.heatshare.utils.queryvo.TempPointDataCustomizedQuery;
import com.nari.heatshare.utils.queryvo.TempPointDataStatisExtendQuery;
import com.nari.platform.date.CalendarUtils;
import com.nari.platform.model.PageCond;
import com.nari.platform.model.ResultWithPageCond;
import com.nari.platform.sqlfunc.mysql.DateFunctionUtils4MySQL;
import com.nari.platform.utils.StringUtils;
import com.nari.rescontroller.dao.IResourceAccessControlDao;

/**
 * 
 * @author Xiaopeng
 * @date 2014-12-10
 */
public class TempPointDataJdbcDaoImpl extends AbstractDaoImpl 
		implements ITempPointDataJdbcDao {
	private Logger logger = Logger.getLogger(TempPointDataJdbcDaoImpl.class);
	private IResourceAccessControlDao iResourceAccessControlDao;
	
	/**
	 * 分页查询温度点数据定制查询列表
	 * @param projectUID
	 * @param communityUID
	 * @param buildingUID
	 * @param recordTimeStart
	 * @param recordTimeEnd
	 * @param pageCond
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2015-1-2
	 */
	public ResultWithPageCond<TempPointDataCustomizedQuery> queryCustomizedQueryPage(String projectUID, 
			String communityUID, String buildingUID, Date recordTimeStart, Date recordTimeEnd,
			PageCond pageCond) throws Exception {
		Date startTime = CalendarUtils.getMinCalBasedSrcCal(CalendarUtils.getInstance(recordTimeStart));
		Date endTime = CalendarUtils.getMaxCalBasedSrcCal(CalendarUtils.getInstance(recordTimeEnd));
		String querySQL = "select tp.t_building_id as buildingUID," +
								 DateFunctionUtils4MySQL.dateSqlField2StringFunc("inner_grep.t_recordTime")+" as recordDate," +
								 "count(inner_grep.t_seriousNum) as tempPointDataCounter," +
								 "tp.t_community_id as communityUID," +
								 "tp.t_project_id as projectUID " +
						  "from (select inner_tpd.t_concentratorNo as t_concentratorNo," +
						  			   "inner_tpd.t_seriousNum as t_seriousNum," +
						  			   "inner_tpd.t_recordTime as t_recordTime " +
						  	    "from p_temperature_point_data inner_tpd " +
						  	    "where inner_tpd.t_recordTime between  '"+CalendarUtils.parseDateTimeToString(startTime)+"' " +
						  	    							 "and '"+CalendarUtils.parseDateTimeToString(endTime)+"') inner_grep, p_temperature_point_info tp " +
						  "where 1=1";
		//权限资源匹配
		String authorityRes = iResourceAccessControlDao.queryAuthorityProjResSql();
		if(!"".equals(authorityRes)) { //非管理员用户授权项目权限
			List<Object> projectUIDList = this.jdbcTemplate.queryForList(authorityRes, Object.class);
			String formatProjectUIDList = StringUtils.formatIDsByList(projectUIDList);
			formatProjectUIDList = StringUtils.formatIDListWithSyntax(formatProjectUIDList, ",", "'");
			querySQL += " and tp.t_project_id in("+formatProjectUIDList+")";
		}
		//设置查询字段
		if(projectUID!=null && !"".equals(projectUID)) {
			querySQL += " and tp.t_project_id='"+projectUID+"'";
		}
		if(communityUID!=null && !"".equals(communityUID)) {
			querySQL += " and tp.t_community_id='"+communityUID+"'";
		}
		if(buildingUID!=null && !"".equals(buildingUID)) {
			querySQL += " and tp.t_building_id='"+buildingUID+"'";
		}
		//设置表关联
		querySQL += " and inner_grep.t_concentratorNo=tp.t_concentrator_no " +
				"and inner_grep.t_seriousNum=tp.t_serious_num";
		//定制查询分组
		querySQL += " group by tp.t_building_id,"+DateFunctionUtils4MySQL.dateSqlField2StringFunc("inner_grep.t_recordTime")+",tp.t_community_id,tp.t_project_id" +
				" having count(inner_grep.t_seriousNum)>0";
		//结果集个数查询
		String couterSQL = "select count(*) from ("+querySQL+") inner_counter";
		System.out.println("couterSQL:"+couterSQL);
		int total = this.jdbcTemplate.queryForInt(couterSQL);
		//定制查询排序及分页
		querySQL += " order by recordDate desc,tp.t_building_id asc " +
				"limit "+pageCond.getStart()+","+pageCond.getLimit();
		logger.debug("querySQL:"+querySQL);
		System.out.println("querySQL:"+querySQL);
		//封装查询结果
		final List<TempPointDataCustomizedQuery> customizedQueryList = new ArrayList<TempPointDataCustomizedQuery>();
		this.jdbcTemplate.query(querySQL, new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				TempPointDataCustomizedQuery customizedQuery = new TempPointDataCustomizedQuery();
				customizedQuery.setProjectUID(rs.getString("projectUID"));
				customizedQuery.setCommunityUID(rs.getString("communityUID"));
				customizedQuery.setBuildingUID(rs.getString("buildingUID"));
				customizedQuery.setRecordDate(rs.getString("recordDate"));
				customizedQuery.setTempPointDataCounter(rs.getInt("tempPointDataCounter"));
				//楼栋所属温度点个数
				String tpCounterSQL = "select count(*) from p_temperature_point_info tp " +
						"where tp.t_building_id='"+customizedQuery.getBuildingUID()+"'";
				int tempPointNum = getJdbcTemplate().queryForInt(tpCounterSQL);
				customizedQuery.setTempPointNum(tempPointNum);
				customizedQueryList.add(customizedQuery);
			}
		});
		//构造返回类型
		pageCond.setTotal(total);
		ResultWithPageCond<TempPointDataCustomizedQuery> customizedQueryPage = new ResultWithPageCond<TempPointDataCustomizedQuery>();
		customizedQueryPage.setList(customizedQueryList);
		customizedQueryPage.setPageCond(pageCond);
		return customizedQueryPage;
	}
	
	/**
	 * 根据温度点数据批次UID查询其对应的档案资料扩展信息
	 * @param meterDataStatisUIDList 温度点数据批次UID列表
	 * 格式：XXX,XXX,XXX
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2015-1-25
	 */
	public Map<String, TempPointDataStatisExtendQuery> queryTpdStatisExtend(String meterDataStatisUIDList) throws Exception {
		//分配表表号列表格式化
		String meterDataStaisUIDListFormat = StringUtils.formatIDListWithSyntax(meterDataStatisUIDList, ",", "'");
		String querySQL = "select tpds.ID as meterDataStatisUID," +
								 "tpds.t_concentratorNo as concentratorNo," +
								 "b.t_building_no as buildingCode," +
								 "b.t_building_area as buildingArea " +
						  "from p_temppointdata_statis tpds," +
						  	   "base_concentrator_info con," +
						  	   "base_building_info b " +
						  "where tpds.ID in("+meterDataStaisUIDListFormat+") " +
						  "and tpds.t_concentratorNo=con.t_concentrator_no " +
						  "and con.t_building_id=b.ID";
		logger.debug("querySQL:"+querySQL);
		System.out.println("querySQL:" + querySQL);
		//封装查询结果
		final Map<String, TempPointDataStatisExtendQuery> extendQueryMap = new HashMap<String, TempPointDataStatisExtendQuery>();
		this.jdbcTemplate.query(querySQL, new RowCallbackHandler() {
			public void processRow(ResultSet rs) throws SQLException {
				try {
					ResultSetMapHandler<TempPointDataStatisExtendQuery> mapper = new ResultSetMapHandler<TempPointDataStatisExtendQuery>();
					//注意：这里已完成了ResultSet的迭代(取代了Spring JDBC的迭代处理)
					List<TempPointDataStatisExtendQuery> tpdStatisExtendList = mapper.mapResultSet2Object(rs, TempPointDataStatisExtendQuery.class);
					if(tpdStatisExtendList!=null && tpdStatisExtendList.size()>0) {
						for(TempPointDataStatisExtendQuery tpdStatisExtend: tpdStatisExtendList) {
							extendQueryMap.put(tpdStatisExtend.getMeterDataStatisUID(), tpdStatisExtend);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.error(e.getMessage());
					throw new SQLException(e.getMessage());
				}
			}
		});
		return extendQueryMap;
	}

	/**
	 * @return the iResourceAccessControlDao
	 */
	public IResourceAccessControlDao getiResourceAccessControlDao() {
		return iResourceAccessControlDao;
	}

	/**
	 * @param iResourceAccessControlDao the iResourceAccessControlDao to set
	 */
	public void setiResourceAccessControlDao(
			IResourceAccessControlDao iResourceAccessControlDao) {
		this.iResourceAccessControlDao = iResourceAccessControlDao;
	}
	
}
